<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员人脸识别离馆 - 校园智能生活助手</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Arial', sans-serif;
        }
        
        .face-recognition-container {
            position: relative;
            width: 100vw;
            height: 100vh;
            overflow: hidden;
        }
        
        .video-container {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: #000;
        }
        
        #video {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.3);
            z-index: 10;
        }
        
        .face-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 10;
        }
        
        .background-blur {
            filter: blur(10px);
            transition: filter 0.3s ease;
        }
        
        .control-panel {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 20;
            text-align: center;
            color: white;
        }
        
        .face-frame {
            width: 300px;
            height: 300px;
            border: 3px solid #ffc107;
            border-radius: 50%;
            margin: 0 auto 30px;
            position: relative;
            overflow: hidden;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
        }
        
        .face-frame::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 280px;
            height: 280px;
            border: 2px dashed #ffc107;
            border-radius: 50%;
            animation: rotate 3s linear infinite;
        }
        
        @keyframes rotate {
            from { transform: translate(-50%, -50%) rotate(0deg); }
            to { transform: translate(-50%, -50%) rotate(360deg); }
        }
        
        .status-text {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 20px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
        }
        
        .instruction-text {
            font-size: 16px;
            margin-bottom: 30px;
            opacity: 0.9;
        }
        
        .btn-exit {
            position: absolute;
            top: 30px;
            right: 30px;
            z-index: 30;
            background: rgba(255, 255, 255, 0.2);
            border: 2px solid white;
            color: white;
            padding: 10px 20px;
            border-radius: 25px;
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .btn-exit:hover {
            background: rgba(255, 255, 255, 0.3);
            color: white;
            text-decoration: none;
        }
        
        .recognition-btn {
            background: linear-gradient(45deg, #ffc107, #ff8c00);
            border: none;
            color: white;
            padding: 15px 40px;
            font-size: 18px;
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(255, 193, 7, 0.3);
        }
        
        .recognition-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(255, 193, 7, 0.4);
        }
        
        .recognition-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .result-message {
            position: absolute;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 25;
            padding: 15px 30px;
            border-radius: 25px;
            font-weight: bold;
            min-width: 300px;
            text-align: center;
        }
        
        .success-message {
            background: rgba(40, 167, 69, 0.9);
            color: white;
            border: 2px solid #28a745;
        }
        
        .error-message {
            background: rgba(220, 53, 69, 0.9);
            color: white;
            border: 2px solid #dc3545;
        }
        
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
            margin-right: 10px;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="face-recognition-container">
        <div class="video-container">
            <video id="video" autoplay muted></video>
        </div>
        
        <div class="overlay"></div>
        
        <a href="{{ url_for('admin') }}" class="btn-exit">
            <i class="fas fa-times"></i> 退出
        </a>
        
        <div class="control-panel">
            <div class="face-frame"></div>
            <div class="status-text" id="statusText">请将面部对准摄像头</div>
            <div class="instruction-text">确保光线充足，面部清晰可见</div>
            <button class="recognition-btn" id="recognitionBtn" onclick="startRecognition()">
                <i class="fas fa-sign-out-alt"></i> 开始离馆识别
            </button>
        </div>
        
        <div id="resultMessage" class="result-message" style="display: none;"></div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let video;
        let isRecognizing = false;
        
        // 初始化摄像头
        async function initCamera() {
            try {
                video = document.getElementById('video');
                const stream = await navigator.mediaDevices.getUserMedia({ 
                    video: { 
                        width: { ideal: 1280 },
                        height: { ideal: 720 },
                        facingMode: 'user'
                    } 
                });
                video.srcObject = stream;
                
                document.getElementById('statusText').textContent = '摄像头已就绪，可以开始识别';
            } catch (err) {
                console.error('摄像头初始化失败:', err);
                document.getElementById('statusText').textContent = '摄像头初始化失败，请检查权限';
                showMessage('摄像头初始化失败，请检查浏览器权限设置', 'error');
            }
        }
        
        // 开始人脸识别
        async function startRecognition() {
            if (isRecognizing) return;
            
            isRecognizing = true;
            const btn = document.getElementById('recognitionBtn');
            const statusText = document.getElementById('statusText');
            
            btn.disabled = true;
            btn.innerHTML = '<div class="loading"></div>正在识别...';
            statusText.textContent = '正在进行人脸识别，请保持静止';
            
            try {
                // 捕获当前视频帧
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                canvas.width = video.videoWidth;
                canvas.height = video.videoHeight;
                context.drawImage(video, 0, 0);
                
                // 转换为base64
                const imageData = canvas.toDataURL('image/jpeg', 0.8);
                
                // 发送到后端进行识别
                const response = await fetch('/admin/face_recognition/library_exit', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        image: imageData
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    statusText.textContent = '离馆成功！';
                    showMessage(`${result.student_name} 离馆成功！座位 ${result.seat_info.seat_number} 已释放`, 'success');
                    
                    // 3秒后返回管理页面
                    setTimeout(() => {
                        window.location.href = '/admin';
                    }, 3000);
                } else {
                    statusText.textContent = '识别失败，请重试';
                    showMessage(result.message || '人脸识别失败，请重试', 'error');
                }
            } catch (error) {
                console.error('识别过程出错:', error);
                statusText.textContent = '识别过程出错，请重试';
                showMessage('识别过程出错，请检查网络连接', 'error');
            } finally {
                isRecognizing = false;
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-sign-out-alt"></i> 开始离馆识别';
                
                // 如果不是成功状态，5秒后重置状态文本
                if (!document.getElementById('statusText').textContent.includes('成功')) {
                    setTimeout(() => {
                        statusText.textContent = '请将面部对准摄像头';
                    }, 5000);
                }
            }
        }
        
        // 显示消息
        function showMessage(message, type) {
            const messageDiv = document.getElementById('resultMessage');
            messageDiv.textContent = message;
            messageDiv.className = `result-message ${type === 'success' ? 'success-message' : 'error-message'}`;
            messageDiv.style.display = 'block';
            
            // 5秒后隐藏消息
            setTimeout(() => {
                messageDiv.style.display = 'none';
            }, 5000);
        }
        
        // 页面加载完成后初始化摄像头
        window.addEventListener('load', initCamera);
        
        // 人脸检测和背景模糊效果
        function detectFaceAndBlur() {
            // 这里应该集成人脸检测库，比如face-api.js
            // 为了演示，我们模拟人脸检测
            const faces = []; // 实际应该是人脸检测结果
            
            if (faces.length > 0) {
                // 如果检测到人脸，移除背景模糊效果（保持人脸清晰）
                video.classList.remove('background-blur');
            } else {
                // 如果没有检测到人脸，添加背景模糊效果
                video.classList.add('background-blur');
            }
        }
        
        // 页面卸载时关闭摄像头
        window.addEventListener('beforeunload', () => {
            if (video && video.srcObject) {
                const tracks = video.srcObject.getTracks();
                tracks.forEach(track => track.stop());
            }
        });
    </script>
</body>
</html>